#include "term.h"
#include <sstream>

Term::Term(int cf, int pow) {
    coef = cf;
    this->power = pow;
}

Term::Term(const std::string& inp) {
    coef = 1;
    power = 1;
    std::stringstream stream(inp);
    stream >> *this;
}

bool operator<(const Term& t1, const Term& t2) {
    return t1.power < t2.power;
}

Term operator+(const Term& t1, const Term& t2) {
    if (t1.power == t2.power) {
        int cfsum = t1.coef + t2.coef;
        return Term(cfsum, t1.power);
    } else {
        return Term();
    }
}

Term operator*(const Term& t1, const Term& t2) {
    Term res;
    res.coef = t1.coef * t2.coef;
    res.power = t1.power + t2.power;
    return res;
}

std::istream& operator>>(std::istream& is, Term& t) {
    int cf = 1;
    int pow;
    if (isdigit(is.peek()) || is.peek() == '-') {
        is >> cf;
    }
    if (is.peek() == 'x') {
        char x;
        is >> x;
        if (is.peek() == '^') {
            is.ignore();
            is >> pow;
        } else {
            pow = 1;
        }
    } else {
        pow = 0;
    }
    t.coef = cf;
    t.power = pow;
    return is;
}

std::ostream& operator<<(std::ostream& os, const Term& t) {
    if (t.coef == 0) {
        os << "0";
    } else {
        if (t.power == 0) {
            os << t.coef;
        } else if (t.power == 1) {
            if (t.coef != 1) {
                os << t.coef;
            }
            os << "x";
        } else {
            if (t.coef != 1) {
                os << t.coef;
            }
            os << "x^" << t.power;
        }
    }
    return os;
}